import websocket
import requests
import json
import numpy as np
from urllib.request import urlopen
try:
    import thread
except ImportError:
    import _thread as thread
import time

matching_list = {}

def on_message(ws, message):
    if message == '#1':
        ws.send('#2')
    else:
        data = json.loads(message)
        data = data['data']
        if data['channel'] == 'match':
            
            data = data['data']
            odds_list = np.array(data['odds'])
            for odds in odds_list:
                match_id = odds['match_id']
                ##如果在已获取的列表中
                # if match_id in matching_list.keys():
                if match_id == 37435358:
                    match = matching_list[match_id]
                    match_odds = match['odds']
                    match_team = match['team']
                    item = match_odds[odds['id']]
                    ##如果玩法属于输赢类型
                    if item['group_short_name'] == 'Winner' and item['match_stage'] == 'map1':
                        # if odds['status'] == 1:
                        bh = round(float(odds['odds']) - float(item['odds']),2)
                        print(
                            '队伍【'+match_team[item['team_id']]['team_name']+'】'+
                            match['game_name']+':'+match['match_name']+item['group_name']+
                            '赔率变化为'+odds['odds']+'['+str(bh)+']'+'\r\n'+
                            'status:',odds['status']
                        )
                        localtime = time.asctime( time.localtime(time.time()) )
                        print ("本地时间为 :", localtime)
                        # else:
                        #     print(
                        #         match['game_name']+':'+match['match_name']+item['group_name']+
                        #         '状态变化为'+odds['status']+'['+str(bh)+']'+
                        #         '队伍【'+match_team[item['team_id']]['team_name']+'】'
                        #     )
                        print('\r\n')
                    matching_list[match_id]['odds'][odds['id']]['odds']     = odds['odds']
                    matching_list[match_id]['odds'][odds['id']]['status']   = odds['status']

                    with open("test.txt","w") as f:
                        f.write(json.dumps(matching_list, sort_keys=True, indent=2))  # 自带文件关闭功能，不需要再写f.close()
        else:
            print(data)

def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")
    clientInit()

def on_open(ws):
    def run(*args):
        time.sleep(1)
        ws.send('{"event":"#handshake","data":{"authToken":null},"cid":22}')
        ws.send('{"event":"#subscribe","data":{"channel":"match"},"cid":2}')
        # ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())
def clientInit():
    # websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://socket.365raylines.com/socketcluster/",
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)
    ws.run_forever()
def getOdds(match_id):
    url = 'https://gameinfo.365raylines.com/v2/odds?match_id='+str(match_id)
    r = requests.get(url)
    if r.status_code==200:
        res=json.loads(r.text,encoding='utf-8')
        err_code = res['code']
        if err_code == 200:
            result = res['result']
            match_id = result['id']
            odds_list =  result['odds']
            new_odds = {}
            for odds in odds_list:
                new_odds[odds['odds_id']]={
                    'odds_group_id':odds['odds_group_id'],
                    'group_name':odds['group_name'],
                    'odds_id':odds['odds_id'],
                    'team_id':odds['team_id'],
                    'team_name':odds['name'],
                    'group_short_name':odds['group_short_name'],
                    'tag':odds['tag'],
                    'odds':odds['odds'],
                    'status':odds['status'],
                    'match_stage':odds['match_stage'],
                }
            matching_list[match_id]['odds'] = new_odds


def getMatch(url):
    r = requests.get(url)
    if r.status_code==200:
        res=json.loads(r.text,encoding='utf-8')
        err_code = res['code']
        if err_code == 200:
            list = res['result']
            for match in list:
                # if match['enable_parlay'] == 1:
                match_idstr = str(match['id'])
                print(match['tournament_name']+':'+ match['match_name']+'【比赛ID'+match_idstr+'<br>')
                match_id = match['id']
                matching_list[match_id] = {
                    'game_name':match['game_name'],
                    'match_name':match['match_name'],
                    'match_short_name':match['match_short_name'],
                    'team':{},
                    'odds':{}
                }
                match_team = match['team']
                for team in match_team:
                        matching_list[match_id]['team'].update({
                            team['team_id']:{
                            'team_name':team['team_name'],
                            'pos':team['pos'],
                            }
                        })
                getOdds(match_id)

    # responseJson = json.loads(response)


if __name__ == "__main__":
    getMatch('http://gameinfo.365raylines.com/v2/match?page=1&match_type=1')
    print(matching_list)
    with open("test.txt", "w") as f:
        # 自带文件关闭功能，不需要再写f.close()
        f.write(json.dumps(matching_list, sort_keys=True, indent=2))
    # clientInit()
    # message='{"event":"#publish","data":{"channel":"match","data":{"source":"odds","odds":[{"id":42395270,"match_id":37434457,"odds":"1.92","last_update":"1624594550","status":1}]}}}'
    # data = json.loads(message)
    # print(data)
    # print(type(data))
    # print(data['data'])
    # data = data['data']
    # print(type(data))

    # odds = data['data']['odds']
    # print(odds[0])
    # print(type(odds))



